import Taro, { useDidShow, useReachBottom } from "@tarojs/taro";
import React, { useState, useReducer } from "react";
import { View, Text } from "@tarojs/components";
import { AtMessage, AtToast, AtTabs, AtTabsPane } from "taro-ui";
import {
  updateUserAvatar,
  getLikesArticle,
  countFan,
  countConcerned,
  countLiked,
  findMyArticle,
  deleteArticle
} from "./api";
import Card from "../../component/Card";
import "taro-ui/dist/style/components/message.scss";
import "taro-ui/dist/style/components/toast.scss";
import "taro-ui/dist/style/components/tabs.scss";
import css from "./index.module.less";

export default function Index() {
  const host = "http://8.130.123.79:8090";
  function reducer(state, action) {
    switch (action.type) {
      case "userInfo": {
        state = action.userInfo;
        return state;
      }
    }
    throw Error("Unknown action: " + action.type);
  }
  const initialState = {
    avatar:
      "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132",
    concernedNumber: 0,
    created: "",
    email: "",
    fansNumber: 0,
    id: 0,
    status: 0,
    tel: "",
    title: null,
    username: "微信用户",
    uuid: "",
  };
  const [state, dispatch] = useReducer(reducer, initialState);
  const [user, setUser] = useState(initialState);
  const [likeArticles, setLikeArticles] = useState([]);
  const [open, setOpen] = useState(false);
  const [fansNumber, setFansNumber] = useState(0);
  const [concernedNumber, setConcernedNumber] = useState(0);
  const [page, setPage] = useState(1);
  const [size, setSize] = useState(4);
  const [current, setCurrent] = useState(0);
  const [likes, setLikes] = useState(0);
  const [myArticle, setMyArticle] = useState([]);

  useDidShow(() => {
    Taro.getStorage({
      key: "userInfo",
      success: function (res) {
        const userInfo = res.data;
        setUser(userInfo);
        const currentPage = 1;
        setPage(currentPage);
        findMyArticle(userInfo.id, currentPage, size).then((res) => {
          if (res.code === 200) {
            setMyArticle(res.data);
          }
        })

        dispatch({
          type: "userInfo",
          userInfo: res.data,
        });

        countFan(userInfo.id).then((res) => {
          if (res.code === 200) {
            setFansNumber(res.data);
          }
        });

        countConcerned(userInfo.id).then((res) => {
          if (res.code === 200) {
            setConcernedNumber(res.data);
          }
        });

        countLiked(userInfo.uuid).then((res) => {
          if (res.code === 200) {
            setLikes(res.data);
          }
        });
      },
      fail: function (err) {
        console.log(err);
      },
    });
  });

  useReachBottom(() => {
    if (current === 0) {
      const currentPage = page + 1;
      setPage(currentPage);
      findMyArticle(state.id, currentPage, size).then((res) => {
        if (res.code === 200) {
          setMyArticle([...myArticle, ...res.data]);
        }
      })
    }
    if (current === 1) {
      const currentPage = page + 1;
      setPage(currentPage);
      getLikesArticle(state.uuid, currentPage, size).then((res) => {
        if (res.code === 200) {
          setLikeArticles([...likeArticles, ...res.data]);
        }
      });
    }
  });

  const changeAvatar = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
    }).then((res) => {
      const file = res.tempFiles[0];
      console.log(file);
      state.avatar = file.path;
      dispatch({
        type: "userInfo",
        userInfo: state,
      });
      Taro.uploadFile({
        url: host + "/attachment/upload",
        filePath: file.path,
        name: "files",
        success(res) {
          console.log(res);
          if (res.statusCode === 200) {
            const data = JSON.parse(res.data);
            const avatar = data.data[0];
            console.log(avatar);
            state.avatar = avatar;
            dispatch({
              type: "userInfo",
              userInfo: state,
            });
            // 重新修改用户头像
            Taro.setStorage({
              key: "userInfo",
              data: state,
            });
            updateUserAvatar(state).then((res) => {
              console.log(res);
              if (res.code === 200) {
                setOpen(true);
              }
            });
          }
        },
        fail: function (err) {
          console.log("错误", err);
        },
      });
    });
    console.log("修改图片");
  };
  const update = () => {
    Taro.navigateTo({ url: "update/index" });
  };

  const detail = (uuid, liked) => {
    Taro.navigateTo({
      url: `../index/detail/index?uuid=${uuid}&liked=${liked}`,
    });
  };

  const toCheckConcerned = () => {
    Taro.navigateTo({ url: `concerned/index?id=${state.id}` });
    console.log("查看关注者列表");
  };

  const toCheckFan = () => {
    console.log("查看粉丝");
    Taro.navigateTo({ url: `fan/index?id=${state.id}` });
  };
  const tabList = [{ title: "创作" }, { title: "赞过" }];
  const handleClick = (value) => {
    setCurrent(value);
    setPage(1);
    if (value === 1) {
      getLikesArticle(state.uuid, 1, size).then((res) => {
        if (res.code === 200) {
          setLikeArticles(res.data);
        }
      });
    }

    if (value === 0) {
      findMyArticle(state.id, 1, size).then((res) => {
        if (res.code === 200) {
          setMyArticle(res.data);
        }
      })
    }
  };
  const operateArticle = (uuid) => {
    deleteArticle(uuid).then((res) => {
      if (res.code === 200) {
        Taro.atMessage({
          'message': '删除文章成功',
          'type': "success",
        })
      } else {
        Taro.atMessage({
          'message': '删除文章失败',
          'type': "error",
        })
      }
    })
  }
  return (
    <React.Fragment>
      <View className={css.app}>
        <AtMessage />
        <View className={css.head}>
          <AtToast
            isOpened={open}
            text={open ? "修改头像成功" : "修改头像失败"}
            icon="{icon}"
          ></AtToast>
          <View className={css.top}>
            <image
              className={css.img}
              src={state.avatar}
              onClick={changeAvatar}
            />
            <View className={css.name}>
              <Text>{state.username}</Text>
              <Text className={css.text}>{state.title}</Text>
            </View>
          </View>

          <View className={css.bottom}>
            <View className={css.count}>
              <View onClick={toCheckConcerned}>
                <View>{concernedNumber}</View>
                <View>关注</View>
              </View>
              <View onClick={toCheckFan}>
                <View>{fansNumber}</View>
                <View>粉丝</View>
              </View>
              <View>
                <View>{likes}</View>
                <View>点赞</View>
              </View>
            </View>
            <View className={css.update} onClick={update}>
              <Text>编辑资料</Text>
            </View>
          </View>
        </View>
        <View>
          <AtTabs current={current} tabList={tabList} onClick={handleClick}>
            <AtTabsPane current={current} index={0}>
              <View className={css.card}>
                {myArticle.map((result) => {
                  return (
                    <View
                      onClick={() => detail(result.article.uuid, result.liked)}
                      onLongPress={() => operateArticle(result.article.uuid)}
                    >
                      <Card {...result} />
                    </View>
                  );
                })}
              </View>
            </AtTabsPane>
            <AtTabsPane current={current} index={1}>
              <View className={css.card}>
                {likeArticles.map((result) => {
                  return (
                    <View
                      onClick={() => detail(result.article.uuid, result.liked)}
                    >
                      <Card {...result} />
                    </View>
                  );
                })}
              </View>
            </AtTabsPane>
          </AtTabs>
        </View>
      </View>
    </React.Fragment>
  );
}

// wx.showModal({
//   title: '温馨提示',
//   content: '亲，授权微信登录后才能正常使用小程序功能',
//   success(res) {
//     console.log(0)
//     console.log(res)
//     //如果用户点击了确定按钮
//     if (res.confirm) {
//       wx.getUserProfile({
//         desc: '获取你的昵称、头像、地区及性别',
//         success: res => {
//           console.log(res);
//           console.log(1);
//         },
//         fail: res => {
//           console.log(2);
//           console.log(res)
//           //拒绝授权
//           wx.showToast({
//             title: '您拒绝了请求,不能正常使用小程序',
//             icon: 'error',
//             duration: 2000
//           });
//           return;
//         }
//       });
//     } else if (res.cancel) {
//       //如果用户点击了取消按钮
//       console.log(3);
//       wx.showToast({
//         title: '您拒绝了请求,不能正常使用小程序',
//         icon: 'error',
//         duration: 2000
//       });
//       return;
//     }
//   }
// });
